<?php

namespace app\admin\model\kuerp;

use addons\kuerp\model\Flows;
use app\admin\model\Admin;
use app\admin\model\department\Admin as DepartmentAdmin;
use think\Db;
use think\Model;
use traits\model\SoftDelete;
use Exception;

class Commonseal extends Model
{

    use SoftDelete;

    

    // 表名
    protected $name = 'kuerp_common_seal';
    
    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'integer';

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    protected $deleteTime = 'deletetime';

    // 追加属性
    protected $append = [
        'check_time_text',
        'common_seal_text',
        'usedeatil_text',
        'check_status_text',
    ];
    

    
    public function getCommonSealList()
    {
        return ['1' => __('Common_seal 1'), '2' => __('Common_seal 2'), '3' => __('Common_seal 3'), '4' => __('Common_seal 4'),'5' => __('Common_seal 5'),'6' => __('Common_seal 6')];
    }

    public function getUsedeatilList()
    {
        return ['1' => __('Usedeatil 1'), '2' => __('Usedeatil 2'), '3' => __('Usedeatil 3'), '4' => __('Usedeatil 4'), '5' => __('Usedeatil 5')];
    }


    public function getCheckTimeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['check_time']) ? $data['check_time'] : '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }


    public function getCommonSealTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['common_seal']) ? $data['common_seal'] : '');
        $list = $this->getCommonSealList();
        return isset($list[$value]) ? $list[$value] : '';
    }


    public function getUsedeatilTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['usedeatil']) ? $data['usedeatil'] : '');
        $list = $this->getUsedeatilList();
        return isset($list[$value]) ? $list[$value] : '';
    }

    protected function setCheckTimeAttr($value)
    {
        return $value === '' ? null : ($value && !is_numeric($value) ? strtotime($value) : $value);
    }

    public function getCheckStatusList()
    {
        return ['0' => __('Check_status 0'), '1' => __('Check_status 1'), '2' => __('Check_status 2'), '3' => __('Check_status 3')];
    }

    public function getCheckStatusTextAttr($value, $data)
    {
        $value = $value ? $value : $data['check_status'];
        $list = $this->getCheckStatusList();
        return isset($list[$value]) ? $list[$value] : '';
    }

    public function addCommonSeal($params)
    {
        $params['check_status'] = $params['check_status'] ?? 1;
        $admin = Admin::info();
        $params['admin_id'] = $admin->id;
        $params['did'] = 0;
        //获取当前用户所在部门
        $department_ids = DepartmentAdmin::getDepartmentIds($admin->id);
        $params['department_ids'] = $department_ids ? $department_ids[0] : 0;
        //是否在审核流程中
        //获取审批流程
        $flows = Db::name('flows')->where('relation_type', 'common_seal')->where('status', 1)->find();
        if (!empty($flows)){
            $flows['flow_items'] = json_decode($flows['flow_items'], true);
            //判断流程中是否有当前用户审核
            $examine_index = 0;
            foreach ($flows['flow_items'] as $key => $value) {
                if (in_array($params['admin_id'], explode(',',$value['admin_id'])) ) {
                    $examine_index = $key + 1;
                    // break;
                }
            }
            $params['check_flow_id'] = $flows['id'];
            $params['check_step_sort'] = $examine_index;
        }

        $commonseal = new self;

        $result = $commonseal->allowField(true)->save($params);
        if (!$result) {
            throw new Exception($commonseal->getError());
        }
        $lastId = $commonseal->getLastInsID();

        $flow = Flows::getFlowByTypes(Flows::COMMON_SEAL);
        //发送审批通知
        Flows::sendStepRecord($flow, Flows::COMMON_SEAL, $lastId);

        return $lastId;
    }

    public function editCommonSeal($params, $row)
    {
        if($row['check_status'] != 2){
            //获取审批流程
            $flows = Db::name('flows')->where('relation_type', 'common_seal')->where('status', 1)->find();
            if (!empty($flows)){
                $flows['flow_items'] = json_decode($flows['flow_items'], true);
                //判断流程中是否有当前用户审核
                $examine_index = 0;
                foreach ($flows['flow_items'] as $key => $value) {
                    if (in_array($row['admin_id'], explode(',',$value['admin_id'])) ) {
                        $examine_index = $key + 1;
                        // break;
                    }
                }
                // $params['check_flow_id'] = $flows['id'];
                $params['check_step_sort'] = $examine_index;
            }
            $params['check_status'] = $params['check_status'] ?? 1;
            // $params['check_step_sort'] = 0;
            $params['check_uids'] = '';
            $params['check_time'] = 0;
            $params['check_remark'] = '';
            $params['updatetime'] = time();
        }

        $apply = new self;
        // 调用当前模型对应的User验证器类进行数据验证
        $result = $apply->isUpdate(true)->allowField(true)->save($params, ['id' => $row['id']]);
        if (false === $result) {
            // 验证失败 输出错误信息
            throw new Exception($apply->getError());
        }

        return true;
    }

    public function getInfo($id)
    {
        $info = $this->where(['id' => $id])->find();
        //获取附件
        if (!empty($info)) {
            $files = explode(',', $info['file_ids']);
            $fileList = [];
            foreach($files as $file) {
                if (empty($file)) { continue; }
                $nameParts = explode('.', $file);
                $ext = end($nameParts);
                $fileList[] = [
                    'file_path' => cdnurl($file,true),
                    'ext' => $ext,
                    'type' => in_array(strtolower($ext), ['png','jpg','jpeg','gif','bmp','webp']) ? 'image':'file'
                ];
            }
            $info['file_list'] = $fileList;

        }
        return $info;
    }



}
